package com.cdgeekcamp.redas.wechat.component;

import com.cdgeekcamp.redas.lib.core.RedasException;
import com.cdgeekcamp.redas.wechat.config.WeChatConfig;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.cdgeekcamp.redas.lib.core.jsonObject.JsonObject;

import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

@Component
public class WeChatControlCenterThread extends Thread {
    Logger log = LoggerFactory.getLogger(WeChatControlCenterRunner.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    WeChatConfig weChatConfig;

    public void run() {
        Gson gson = new Gson();

        final String uri =
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + weChatConfig.getAppId() + "&secret=" + weChatConfig.getAppSecret();
        log.info(uri);
        try {
            // 以下注释用来消除 while 语句警告提示
            //noinspection InfiniteLoopStatement
            while (true) {
//                String result = restTemplate.getForObject(uri, String.class);
//                String result = "{\"access_token\":\"29_i9Pa1PebEfFTAGhoQK_AqpfI6sxYuTGVQf1qojisEraXl1QtkVcDV_ce7R6vW0g_DtD0-HSWWU6NiuHKzOaTfQ9szCgjwGFMjeb1HBgUjXskY09r4ArTA0AM8JyT3SqmaYRk3HYtlB1qV9mUOFCgAEAHYV\",\"expires_in\":7200}";
                String result = "{\"errcode\":40013,\"errmsg\":\"invalid appid\"}";
                WeChatTokenResponse weChatTokenResponse = gson.fromJson(result, WeChatTokenResponse.class);
                log.info(result);
//                WeChatTokenResponse weChatTokenResponse = restTemplate.getForObject(uri, WeChatTokenResponse.class);
//                assert weChatTokenResponse != null;

                log.info(weChatTokenResponse.getAccessToken());
                log.info(weChatTokenResponse.getExpiresIn().toString());
                log.info(weChatTokenResponse.getErrCode().toString());
                log.info(weChatTokenResponse.getErrMsg());
                TimeUnit.SECONDS.sleep(2);
            }
        } catch (HttpClientErrorException | InterruptedException e) {
            log.error("请求微信API失败");
        }
    }
}
